﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace TSites.EmailEntity.Template
{
	public class EmailTemplateReader
	{
		public static Dictionary<int, Dictionary<string, EmailTemplate>> GetEmailTemplate(string xmlFilePath)
		{
			Dictionary<int, Dictionary<string, EmailTemplate>> dicEmailTemp = null;
			Dictionary<string, EmailTemplate> dicLocale = null;

			XmlDocument xmlDoc = new XmlDocument();
			XmlNodeList templateNodes = null;
			try
			{
				templateNodes = xmlDoc.GetElementsByTagName("template");
				if (templateNodes != null)
				{
					dicEmailTemp = new Dictionary<int, Dictionary<string, EmailTemplate>>();
					EmailTemplate emailTemp = null;
					foreach (XmlNode xmlNode in templateNodes)
					{
						emailTemp = new EmailTemplate();
						emailTemp.ID = int.Parse(xmlNode.Attributes[0].InnerXml);
						emailTemp.Name = xmlNode.Attributes[1].InnerXml;
						emailTemp.Locale = xmlNode.Attributes[2].InnerXml;
						emailTemp.Subject = xmlNode["subject"].InnerXml;
						emailTemp.Template = File.ReadAllText(xmlNode["filepath"].InnerXml, Encoding.UTF8);
						
						// add to HashTable
						if (dicEmailTemp.ContainsKey(emailTemp.ID))
						{
							dicLocale = dicEmailTemp[emailTemp.ID];
							if (!dicLocale.ContainsKey(emailTemp.Locale))
							{
								dicLocale.Add(emailTemp.Locale, emailTemp);
							}
						}
						else
						{
							dicLocale = new Dictionary<string, EmailTemplate>();
							dicLocale.Add(emailTemp.Locale, emailTemp);
							dicEmailTemp.Add(emailTemp.ID, dicLocale);
						}
					}
				}
			}
			catch (Exception)
			{
				throw;
			}
			return dicEmailTemp;
		}
	}
}
